/* eslint-disable no-param-reassign */
import { useStore } from '@/hooks';
import { Button, Dialog, Form, DatePicker, Input, Switch, Message } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid, TitleGrid, DATETIME_TEXT, toSelectDataSource, ENUMS } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';
import TauSimpleSelect from '@/components/TauSimpleSelect';
import QR from '@/components/QR/QR';
import Styles from './DataForm.module.scss';


const FromItem = Form.Item;

const DataForm = ({ modal, username, onCancel, onSubmit }) => {
  const { managersStore: store } = useStore();
  // 使用useRef进行拼接字段且不会造成重绘
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(modal?.show === 'view');
  const [QRModal, setQRModal] = useState({});
  const formProps = isViewMode ? { field: false } : {};
  const [managers] = useState(() => observable({}));
  const [currentNext, setCurrentNext] = useState(false);
  const [cashBackRates, setCashBackRates] = useState({});

  useEffect(() => { if (modal.close?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    if (username) {
      (async () => {
        const cashBackRate = await store.getDictsItems('managerCashBackRate');
        setCashBackRates(cashBackRate);
        const res = await store.get(username);
        editCtx.origin = _.cloneDeep(res);
        _.assign(managers, res);
      })();
    } else {
      _.set(managers, 'independentAccount.period', 0);
      _.set(managers, 'accountManagerInfo.discountInfo.cc', {});
      _.set(managers, 'accountManagerInfo.discountInfo.bus', {});
      _.set(managers, 'accountManagerInfo.discountInfo.sc', {});
      _.set(managers, 'accountManagerInfo.discountInfo.rs', {});
    }
  }, [modal]);

  if (!managers) return <></>;

  const isCompany = managers.accountManagerInfo?.independentAccount?.collectionAccountInformation?.type === 'MERCHANT_ID';
  const isPrice = managers.accountManagerInfo?.independentAccount?.independentAccountType === '1';

  const cc = managers?.accountManagerInfo?.discountInfo?.cc?.type === '1';
  const bus = managers?.accountManagerInfo?.discountInfo?.bus?.type === '1';
  const sc = managers?.accountManagerInfo?.discountInfo?.sc?.type === '1';
  const rs = managers?.accountManagerInfo?.discountInfo?.rs?.type === '1';

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(managers, name, value);
    if (name === 'accountManagerInfo.discountInfo.cc.discountValue.RMB') {
      _.set(managers, 'accountManagerInfo.discountInfo.cc.discountValue.HKD', value);
      _.set(managers, 'accountManagerInfo.discountInfo.cc.discountValue.MOP', value);
    }
    if (name === 'accountManagerInfo.discountInfo.bus.discountValue.RMB') {
      _.set(managers, 'accountManagerInfo.discountInfo.bus.discountValue.HKD', value);
      _.set(managers, 'accountManagerInfo.discountInfo.bus.discountValue.MOP', value);
    }
    if (name === 'accountManagerInfo.discountInfo.sc.discountValue.RMB') {
      _.set(managers, 'accountManagerInfo.discountInfo.sc.discountValue.HKD', value);
      _.set(managers, 'accountManagerInfo.discountInfo.sc.discountValue.MOP', value);
    }
    if (name === 'accountManagerInfo.discountInfo.rs.discountValue.RMB') {
      _.set(managers, 'accountManagerInfo.discountInfo.rs.discountValue.HKD', value);
      _.set(managers, 'accountManagerInfo.discountInfo.rs.discountValue.MOP', value);
    }
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  // 重载definitions中的定义，处理一些根据上下文的动态定义
  const overrideModel = {
    accountManagerInfo: {
      independentAccount: {
        collectionAccountInformation: {
          name: {
            label: isCompany ? t`公司名称` : t`真实姓名`,
            ui: {
              itemProps: { required: isCompany },
            },
          },
          accountIdentification: {
            label: isCompany ? t`公司商户号` : t`账号标识`,
            ui: {
              renderer: (v) => (<Input
                value={v}
                readOnly={!isCompany}
                // disabled={!isCompany}
                placeholder={isCompany ? t`请填写公司商户号` : t`请扫码绑定收款帐号`}
                addonAfter={isCompany || isViewMode ? null : <Button type="primary" onClick={handleQrCode}>{t`扫码设置`}</Button>}
              />),
              itemProps: { required: isCompany },
            },
          },
          type: {
            label: t`分账收款类型`,
            ui: {
              renderer: (v) => <TauSimpleSelect data={toSelectDataSource(ENUMS.bindAccountType)} value={v} />,
            },
          },
        },
        independentAccountValue: {
          label: isPrice ? t`分账金额` : t`分账比例`,
          RMB: {
            label: isPrice ? t`分账金额` : t`分账比例`,
          },
        },
      },
      discountInfo: {
        label: t`分佣信息`,
        disable: {
          label: t`是否禁用`,
          ui: {
            renderer: (v) => {
              return (<Switch
                checked={v}
                size="small"
                autoWidth
                checkedChildren="是"
                unCheckedChildren="否"
              />);
            },
          },
        },
        failureTime: {
          label: t`失效时间`,
          text: DATETIME_TEXT,
          ui: {
            renderer: (v) => <DatePicker type="datetime" showTime value={v} />,
          },
        },
        bus: {
          label: t`巴士分佣信息`,
          type: {
            label: t`巴士分佣类型`,
            ui: {
              renderer: (v) => <TauSimpleSelect className={v ? '' : Styles.red_select_color} data={toSelectDataSource(ENUMS.type)} value={v == undefined ? cashBackRates['busType'] : v} />,
            },
          },
          discountValue: {
            label: t`分佣值<br/> RMB<br/> HKD<br/> MOP`,
            '{RMB}': {
              label: bus ? t`巴士分佣值[key]` : t`巴士分佣比例`,
              ui: {
                renderer: (v) => <Input className={v ? '' : Styles.red_input_color} value={v == undefined ? cashBackRates['bus'] : v} />,
              },
            },
          },
        },
        cc: {
          label: t`包车分佣信息`,
          type: {
            label: t`包车分佣类型`,
            ui: {
              renderer: (v) => <TauSimpleSelect className={v ? '' : Styles.red_select_color} data={toSelectDataSource(ENUMS.type)} value={v == undefined ? cashBackRates['ccType'] : v} />,
            },
          },
          discountValue: {
            label: t`分佣值<br/> RMB<br/> HKD<br/> MOP`,
            '{RMB}': {
              label: cc ? t`包车分佣值[key]` : t`包车分佣比例`,
              ui: {
                renderer: (v) => <Input className={v ? '' : Styles.red_input_color} value={v == undefined ? cashBackRates['cc'] : v} />,
              },
            },
          },
        },
        sc: {
          label: t`专线分佣信息`,
          type: {
            label: t`专线分佣类型`,
            ui: {
              renderer: (v) => <TauSimpleSelect className={v ? '' : Styles.red_select_color} data={toSelectDataSource(ENUMS.type)} value={v == undefined ? cashBackRates['scType'] : v} />,
            },
          },
          discountValue: {
            label: t`分佣值<br/> RMB<br/> HKD<br/> MOP`,
            '{RMB}': {
              label: sc ? t`专线分佣值[key]` : t`专线分佣比例`,
              ui: {
                renderer: (v) => <Input className={v ? '' : Styles.red_input_color} value={v == undefined ? cashBackRates['sc'] : v} />,
              },
            },
          },
        },
        rs: {
          label: t`拼车分佣信息`,
          type: {
            label: t`拼车分佣类型`,
            ui: {
              renderer: (v) => <TauSimpleSelect className={v ? '' : Styles.red_select_color} data={toSelectDataSource(ENUMS.type)} value={v == undefined ? cashBackRates['rsType'] : v} />,
            },
          },
          discountValue: {
            label: t`分佣值<br/> RMB<br/> HKD<br/> MOP`,
            '{RMB}': {
              label: rs ? t`拼车分佣值[key]` : t`拼车分佣比例`,
              ui: {
                renderer: (v) => <Input className={v ? '' : Styles.red_input_color} value={v == undefined ? cashBackRates['rs'] : v} />,
              },
            },
          },
        },
      },
    },
    iphone: {
      label: t`手机号`,
      ui: {
        renderer: (v) => (
          <Input
            autoComplete="off"
            placeholder="请输入手机号"
            value={v}
            addonAfter={modal.show === 'add' && <Button type="primary" onClick={() => current(v)}>{t`下一步`}</Button>}
          />
        ),
        itemProps: { required: true, format: 'tel' },
      },
    },
  };

  const current = async (r) => {
    try {
      if (r.length !== 11) {
        return Message.warning({ content: t`请输入有效手机号` });
      }
      const res = await store.getInetusersMobile({ mobile: r });
      if (JSON.stringify(res) !== '{}') {
        const info = await store.get(res?.username);
        setCurrentNext(true);
        _.assign(managers, info);
      } else {
        Message.warning(t`当前用户非平台用户，请先添加为平台用户！`);
        _.assign(managers, {});
      }
    } catch (error) {
      console.log('🚀 _ file: DataForm.jsx:253 _ error:', error);
    }
  };

  // 扫码绑定用户
  const handleQrCode = async () => {
    try {
      const { fullname } = toJS(managers);
      const baseUrl = await store.addProfitShare(managers);
      setQRModal({
        open: true,
        name: fullname,
        baseUrl,
        okText: '下载',
        onCancel: QROnCancel,
      });
    } catch (error) {
      console.log('🚀 _ file: DataForm.jsx:270 _ error:', error);
    }
  };

  // 关闭二维码
  const QROnCancel = () => {
    setQRModal({ open: false });
  };

  /**
   * @description 提交表单实现修改客户经理
   * @param {*} r formData
   */
  const handleSubmit = (values, errors) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    const discountInfo = toJS(managers).accountManagerInfo?.discountInfo || {};
    _.forEach(discountInfo, (value, key) => {
      if (!(key == 'disable' || key == 'failureTime') && discountInfo[key]) {
        if ((!discountInfo[key]?.type && discountInfo[key]?.discountValue?.RMB) || (discountInfo[key]?.type && !discountInfo[key]?.discountValue?.RMB)) {
          if (!discountInfo[key]?.type) {
            discountInfo[key].type = cashBackRates[`${key}Type`];
          }
          if (!discountInfo[key]?.discountValue?.RMB) {
            discountInfo[key] = {
              ...discountInfo[key],
              discountValue: {
                RMB: cashBackRates[key],
                MOP: cashBackRates[key],
                HKD: cashBackRates[key],
              },
            };
          }
        }
      }
    });

    _.assign(managers, {
      accountManagerInfo: {
        ...managers.accountManagerInfo,
        discountInfo,
      },
    });
    onSubmit?.(managers);
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      inline
      isPreview={isViewMode}
      {...formProps}
      value={managers}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      {(currentNext || modal.show !== 'add') ?
        <>
          <TitleGrid title={t`基本信息`} />
          <FieldsGrid
            formData={managers}
            mode={modal?.show}
            overrideModel={overrideModel}
            fields={['fullname', 'mobile']}
          />
          <TitleGrid title={t`客户经理分佣`} />
          <FieldsGrid
            formData={managers}
            mode={modal?.show}
            overrideModel={overrideModel}
            fields={['cc.type', 'cc.discountValue.{RMB}', 'sc.type', 'sc.discountValue.{RMB}', 'bus.type', 'bus.discountValue.{RMB}', 'rs.type', 'rs.discountValue.{RMB}', 'disable'].map((n) => `accountManagerInfo.discountInfo.${n}`)}
          />
          <TitleGrid title={t`分账信息`} />
          <FieldsGrid
            formData={managers}
            mode={modal?.show}
            overrideModel={overrideModel}
            fields={['period'].map((n) => `accountManagerInfo.independentAccount.${n}`).concat(['type', 'name', 'accountIdentification'].map((n) => `accountManagerInfo.independentAccount.collectionAccountInformation.${n}`))}
          />
        </>
        :
        <FieldsGrid
          formData={managers}
          mode={modal?.show}
          overrideModel={overrideModel}
          fields={['iphone']}
        />
      }
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
      <QR modal={QRModal} />
    </Form>
  );
};

export default observer(DataForm);
